package com.mengtian_tech.smart_farm.service;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.mengtian_tech.smart_farm.model.BaseModel;
import com.mengtian_tech.smart_farm.model.SysUser;
import com.mengtian_tech.smart_farm.util.MyBeanUtils;
import com.mengtian_tech.smart_farm.vo.PageResult;
import com.mengtian_tech.smart_farm.vo.Query;

@Service
public class SystemServiceImpl implements SystemService{
	@PersistenceContext
	private EntityManager entityManager;
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Transactional
	public BaseModel save(BaseModel model) {
		if (StringUtils.isEmpty(model.getId())) {
			model.setId(null);
			model.setCreateDate(new Date());
			model.setDeleted(0);
			model.setUpdateDate(new Date());
			entityManager.persist(model);
			return model;
		} else {
			BaseModel target = this.findById(model.getId(),model.getClass());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(model, target);
				
				System.out.println("copy result:");
				System.out.println(target);
				
				return entityManager.merge(target);
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
				return null;
			}
		}		
	}
	

	@Transactional
	public void delete(BaseModel model) {
		if (!StringUtils.isEmpty(model.getId())) {			
			model = this.findById(model.getId(), model.getClass());
			model.setDeleted(1);
			model.setUpdateDate(new Date());
			entityManager.merge(model);
		}else {
			throw new RuntimeException("删除失败，id为空");
		}
	}



	public <T> T findById(String id, Class<T> clazz) {
		return entityManager.find(clazz, id);
	}


	@SuppressWarnings("unchecked")
	public <T> List<T> findList(Query<T> q)  {
		javax.persistence.Query dbQuery =  entityManager.createQuery(q.getQueryString());
		
		//设置查询条件
		if(q.getWhereValues().size() > 0) {
			for(int i=0;i<q.getWhereValues().size();i++) {
				dbQuery.setParameter(i+1, q.getWhereValues().get(i));
			}
		}
		
		return dbQuery.getResultList();
	}



	public <T> PageResult<T> findPageList(Query<T> q)  {
		PageResult<T> result = new PageResult<T>();
		result.setPageNo(q.getPageNo());
		result.setPageSize(q.getPageSize());
		 
		//查询列表
		javax.persistence.Query dbQuery =  entityManager.createQuery(q.getQueryString());
		//设置查询条件
		if (q.getWhereValues().size() > 0) {
			for (int i = 0; i < q.getWhereValues().size(); i++) {
				dbQuery.setParameter(i+1, q.getWhereValues().get(i));
			}
		}
		//设置分页
		dbQuery.setMaxResults(q.getPageSize());
		dbQuery.setFirstResult((q.getPageNo()-1)*q.getPageSize());
		//查询结果
		@SuppressWarnings("unchecked")
		List<T> list = dbQuery.getResultList();		
		result.setData(list);		
		
		//查询总数
		javax.persistence.Query dbCountQuery = this.entityManager.createQuery(q.getCountString());
		//设置查询条件
		if (q.getWhereValues().size() > 0) {
			for (int i = 0; i < q.getWhereValues().size(); i++) {
				dbCountQuery.setParameter(i+1, q.getWhereValues().get(i));
			}
		}
		Long cnt = (Long) dbCountQuery.getSingleResult();
		result.setTotalCount(cnt);
		
		return result;
	}


	public boolean exist(Query<?> q) {
		javax.persistence.Query dbQuery =  entityManager.createQuery(q.getCountString());
		
		//设置查询参数
		if(q.getWhereValues().size() > 0) {
			for(int i=0;i<q.getWhereValues().size();i++) {
				dbQuery.setParameter(i+1, q.getWhereValues().get(i));
			}
		}
		
		Long cnt = (Long) dbQuery.getSingleResult();
		if(cnt > 0) {
			return true;
		}else {
			return false;
		}
		
	}


 

}
